package com.example.androidcomplete02.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.androidcomplete02.R;

public class FragmentArgument extends Activity {
	EditText mStartNum;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch20_fragmentargument);
		mStartNum = (EditText) findViewById(R.id.startnum);
	}

	public void mOnClick(View v) {
		if (v.getId() == R.id.btnadd) {
			FragmentTransaction tr = getFragmentManager().beginTransaction();
			Bundle args = new Bundle();
			args.putInt("start",
					Integer.parseInt(mStartNum.getText().toString()));
			CounterFragment cf = new CounterFragment();
			cf.setArguments(args);
			tr.add(R.id.frame, cf, "counter");
			tr.commit();
		}
	}

	public static class CounterFragment extends Fragment {
		public static CounterFragment newInstance(int start) {
			CounterFragment cf = new CounterFragment();
			Bundle args = new Bundle();
			args.putInt("start", start);
			cf.setArguments(args);
			return cf;
		}

		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View root = inflater.inflate(R.layout.counterfrg, container,
					false);
			Button btnIncrease = (Button) root
					.findViewById(R.id.btnincrease);
			final TextView textCnt = (TextView) root
					.findViewById(R.id.txtcounter);
			Bundle args = getArguments();
			int start = args.getInt("start");
			textCnt.setText(Integer.toString(start));
			btnIncrease.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					int count = Integer.parseInt(textCnt.getText().toString());
					textCnt.setText(Integer.toString(count + 1));
				}
			});
			return root;
		}
	}
}
